import * as signalR from '@microsoft/signalr'
import { getToken } from '../library/cookieUtil'
import { systemConfig } from "./config"
import { layer } from "@layui/layer-vue"
import  Util  from "./Util"

export default {
  SR: {} as signalR.HubConnection,
  init() {
    const connection = new signalR.HubConnectionBuilder()
      .withUrl(systemConfig.msgHub, { accessTokenFactory: () => getToken() as string })
      .withAutomaticReconnect({
        nextRetryDelayInMilliseconds: () => {          
          return 5000; // 每5秒重连一次
        },
      }) //自动重新连接
      .configureLogging(signalR.LogLevel.Warning)
      .build();

    connection.keepAliveIntervalInMilliseconds = 15 * 1000; // 心跳检测15s
    connection.serverTimeoutInMilliseconds = 30 * 60 * 1000; // 超时时间30m

    // 启动连接
    connection.start().then(() => {
      //console.log("signalR-启动成功");
      layer.notifiy({
        title: `欢迎`,
        content: Util.randomGreetings(),
        time: 10000,
        icon:1,
        area:['350px'],offset:'rb',
      })
    });

    // 接收聊天数据
    connection.on('welcome', (data) => {
      // layer.notifiy({
      //   title: `来自系统的消息通知`,
      //   content: `${data}`,offset:'rb',
      // })
    })

    // 接收后台手动推送消息
    connection.on("receiveNotice", (data) => {
      layer.notifiy({
        title: data.title,
        time: 5000,
        content: data.content
      })
    })
    // 接收聊天数据
    connection.on('receiveChat', (data) => {
      layer.notifiy({
        title: `来自${data.userName}的消息通知`,
        content: data.message
      })
    })

    // 断开连接
    connection.onclose(async () => {
      layer.notifiy({
        title: `连接断开`,
        content: '',
        time: 2000,
        icon:2
      })
    });
    // 重连中
    connection.onreconnecting(async () => {
      layer.msg("服务器已断线...", { icon: 16, time: 5000 })
      //await this.start()
    });
    // 重连成功
    connection.onreconnected(() => {
      layer.notifiy({
        title: `重连成功`,
        content: '',
        time: 2000,
        icon:1
      })
    });

    const reciveMessage = (msg: any) => {
      layer.notifiy({
        title: `接收消息`,
        content: msg,
        time: 10000,
        icon:1
      })
    };

    // 接收消息
    connection.on('ReceiveMessage', reciveMessage);

  },
  // failNum:4,
  // /**
  //  * 调用方法 this.signalR.start().then(async () => { await this.SR.invoke("method")})
  //  * @returns
  //  */
  //  async start() {
  //   try {
  //     if (this.SR.state === signalR.HubConnectionState.Disconnected) {
  //       await this.SR.start()
  //     }
  //     return true
  //   } catch (error) {
  //     this.failNum--
  //     if (this.failNum > 0) {
  //       setTimeout(async () => {
  //         await this.start()
  //       }, 5000)
  //     }
  //     return false
  //   }
  // },

}